﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Intorise.MiniDB.ClassLibrary
{
    internal class Log
    {
        static FileInfo logFile = null;
        static FileStream stream = null;
        static object locker = new object();
        static Queue<string> queue = new Queue<string>();

        static Log()
        {
            bool createdNew;
            Mutex mutex = new Mutex(true, @"Global\LogMutext", out createdNew);
            if (!createdNew)
            {
                mutex.WaitOne();
            }
            string logRootDir = Helper.RootDir + "\\log";
            if (!Directory.Exists(logRootDir))
            {
                Directory.CreateDirectory(logRootDir);
            }
            mutex.ReleaseMutex();
            mutex.Close();

            logFile = new FileInfo(logRootDir + "\\" + DateTime.Now.ToString("yyyyMMdd") + "-" + DateTime.Now.Ticks + "log");
        }

        /// <summary>
        /// Write message to file,do not append DateTime.
        /// </summary>
        /// <param name="message"></param>
        public static void Write(string message)
        {
            queue.Enqueue(DateTime.Now.ToString("yyyyMMdd hh:mm:ss")+" "+message);
            Task.Factory.StartNew(() =>
            {
                stream = logFile.Open(FileMode.Append, FileAccess.Write, FileShare.Read);
                byte[] data = Encoding.Default.GetBytes(queue.Dequeue());
                stream.Write(data, 0, data.Length);
            });
        }

        ~Log()
        {
            try
            {
                stream.Close();
            }
            catch
            {

            }
        }
    }
}
